<template>
  <div class="app">
    <div class="title">
      <div class="icon" @click="hanldeBack">
        <el-icon><ArrowLeftBold /></el-icon>
      </div>
      <div class="title-left">印刷报工单</div>
      <div class="title-right" @click="hanldeReportList">报工记录</div>
    </div>
    <div style="margin-top: 20px">
      <el-form
        :model="form"
        :rules="rules"
        :disabled="flag"
        ref="userRef"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-form-item label="机台" prop="machineName">
            <el-input
              style="width: 100%"
              v-model="form.machineName"
              readonly
              placeholder="请选择机台"
              @click="openDialog"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item label="机长" prop="headName">
            <el-input
              style="width: 100%"
              v-model="form.headName"
              readonly
              placeholder="自动带出"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item label="上报人" prop="createBy">
            <el-input
              style="width: 100%"
              v-model="form.createBy"
              placeholder="请输入"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item label="报工日期" prop="reportDate">
            <el-date-picker
              style="width: 88%"
              v-model="form.reportDate"
              type="date"
              :editable="false"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-row>
        <el-row :gutter="20">
          <el-form-item label="当班日期" prop="dutyDate">
            <el-date-picker
              style="width: 88%"
              v-model="form.dutyDate"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
        </el-row>
      </el-form>
    </div>

    <el-collapse v-model="activeNames">
      <el-collapse-item disabled title="保养明细" name="1">
        <template #title>
          <el-icon style="color: #4479f6">
            <Position />
          </el-icon>
          <span class="title">保养明细</span>
        </template>
        <div class="order-form">
          <el-form
            :model="data"
            ref="reportCareListForm"
            :disabled="flag"
            class="data-form"
          >
            <el-table :data="data.reportCareList" border>
              <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
              />
              <el-table-column
                label="保养单编码"
                width="300"
                prop="code"
                align="center"
              ></el-table-column>
              <el-table-column
                label="时长(h)"
                width="150"
                prop="timeLength"
                align="center"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.timeLength"
                    type="number"
                    pattern="[0-9]*"
                    placeholder="请输入时长(h)"
                  >
                    <template #append>h</template>
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="备注"
                width="200"
                prop="remark"
                align="center"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.remark"
                    placeholder="请输入内容"
                  ></el-input>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-collapse-item>
      <el-collapse-item disabled title="人员明细" name="2">
        <template #title>
          <el-icon style="color: #4479f6">
            <Position />
          </el-icon>
          <span class="title">人员明细</span>
        </template>
        <el-button
          size="small"
          type="primary"
          style="margin-bottom: 10px"
          v-if="!route.query.info"
          @click="handleAddReportUserList"
        >
          选择人员
        </el-button>
        <div class="order-form">
          <el-form
            :model="data"
            ref="reportUserListForm"
            :disabled="flag"
            class="data-form"
          >
            <el-table
              :data="data.reportUserList"
              ref="reportUserListRef"
              border
              :row-class-name="tableRowClassName"
              :summary-method="getSummaries"
              show-summary
            >
              <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
              />
              <!-- <el-table-column
                                label="工位"
                                min-width="100"
                                prop=""
                                align="center"
                            ></el-table-column> -->
              <el-table-column
                label="员工工号"
                min-width="160"
                prop="no"
                align="center"
              ></el-table-column>
              <el-table-column
                label="计件工资(元)"
                min-width="150"
                prop="wagesPiece"
                align="center"
              >
                <!-- <template #default="scope">
                                    <el-form-item
                                        :prop="'reportUserList.' + scope.$index + '.wagesPiece'"
                                        :rules="[
                                            {
                                                required: true,
                                                message: '计件工资',
                                                trigger: 'blur',
                                            },
                                        ]"
                                    >
                                        <el-input
                                            @blur="changeWagesSum(scope.row, scope.$index)"
                                            v-model="scope.row.wagesPiece"
                                            type="number"
                                            placeholder="请输入计件工资(元)"
                                        >
                                            <template #append>元</template>
                                        </el-input>
                                    </el-form-item>
                                </template> -->
              </el-table-column>
              <!-- <el-table-column
                                label="补助工资(元)"
                                min-width="160"
                                prop="wagesSubsidy"
                                align="center"
                            >
                                <template #default="scope">
                                    <el-form-item
                                    >
                                        <el-input
                                            @blur="changeWagesSum(scope.row, scope.$index)"
                                            v-model="scope.row.wagesSubsidy"
                                            type="number"
                                            placeholder="请输入补助工资(元)"
                                        >
                                            <template #append>元</template>
                                        </el-input>
                                    </el-form-item>
                                </template>
                            </el-table-column> -->
              <!-- <el-table-column
                                label="合计工资(元)"
                                min-width="120"
                                prop="wagesSum"
                                align="center"
                            ></el-table-column> -->
              <el-table-column
                prop="proportion"
                label="岗位占比"
                align="center"
              >
                <template #default="scope">
                  <el-input
                    type="number"
                    pattern="[0-9]*"
                    @input="limitInput('proportion', scope.row)"
                    :disabled="flag"
                    v-model="scope.row.proportion"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                v-if="!flag"
                align="center"
                fixed="right"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDelete(scope.row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-collapse-item>
      <el-collapse-item disabled title="完成工作量明细" name="3">
        <template #title>
          <el-icon style="color: #4479f6">
            <Position />
          </el-icon>
          <span class="title">完成工作量明细</span>
        </template>
        <el-button
          size="small"
          type="primary"
          style="margin-bottom: 10px"
          v-if="!route.query.info"
          @click="handleAddPieceList"
        >
          选择生产单
        </el-button>
        <div class="order-form">
          <el-form
            :model="data"
            ref="reportWorkListForm"
            :disabled="flag"
            class="data-form"
          >
            <el-table
              :data="data.reportWorkList"
              ref="reportWorkListRef"
              border
              :header-cell-class-name="mustReport"
              :summary-method="getSummariesWorkList"
              show-summary
            >
              <el-table-column
                label="序号"
                width="60"
                type="index"
                align="center"
              />
              <el-table-column
                label="类型"
                align="center"
                width="80"
                prop="type"
              >
                <template v-slot="{ row }">
                  <el-tag :type="row.type == 1 ? 'success' : ''" effect="dark">
                    {{ row.type == 1 ? "封面" : "内文" }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                label="生产单编码"
                min-width="150"
                align="center"
                prop="produceCode"
              ></el-table-column>
              <el-table-column
                label="书刊编码"
                width="120"
                prop="bookCode"
                align="center"
              ></el-table-column>
              <el-table-column
                label="书刊名称"
                width="160"
                prop="orderName"
                align="center"
              ></el-table-column>
              <el-table-column
                label="品种"
                width="160"
                prop="breed"
                align="center"
              ></el-table-column>
              <el-table-column
                label="下单日期"
                min-width="120"
                align="center"
                prop="orderTime"
              >
                <template v-slot="{ row }">
                  {{ row.orderTime ? row.orderTime.split("T")[0] : "" }}
                </template>
              </el-table-column>
              <el-table-column label="印刷方式" align="center" prop="printType">
                <template #default="scope">
                  <dict-tag
                    :options="mes_paper_package"
                    :value="scope.row.printType"
                  />
                </template>
              </el-table-column>
              <el-table-column label="印色" align="center" prop="printColor">
                <template #default="scope">
                  <dict-tag
                    :options="ems_order_print_color"
                    :value="scope.row.printColor"
                  />
                </template>
              </el-table-column>
              <el-table-column
                label="印张"
                align="center"
                prop="sheet"
              ></el-table-column>
              <el-table-column
                label="贴标"
                align="center"
                prop="labeling"
              ></el-table-column>
              <el-table-column
                label="印数"
                align="center"
                prop="printAmount"
              ></el-table-column>

              <el-table-column
                label="完成数量"
                min-width="120"
                align="center"
                prop="finishNum"
              >
                <template #default="scope">
                  <!-- <el-form-item :prop="'reportUserList.' + scope.$index + '.wagesPiece'"
                                            :rules="[{ required: true, message: '计件工资', trigger: 'blur' }]"> -->
                  <el-input
                    pattern="[0-9]*"
                    @blur="changePieceLing(scope.row, scope.$index)"
                    v-model="scope.row.finishNum"
                    type="number"
                    placeholder="请输入完成数量"
                  ></el-input>
                  <!-- </el-form-item> -->
                </template>
              </el-table-column>
              <el-table-column
                label="计件令数"
                align="center"
                prop="pieceLing"
              ></el-table-column>
              <el-table-column
                label="计件标准"
                min-width="120"
                align="center"
                prop="standard"
              >
                <template #default="scope">
                  <!-- <el-form-item :prop="'reportUserList.' + scope.$index + '.wagesPiece'"
                                            :rules="[{ required: true, message: '计件工资', trigger: 'blur' }]"> -->
                  <el-input
                    pattern="[0-9]*"
                    @blur="changeAmount(scope.row, scope.$index)"
                    v-model="scope.row.standard"
                    type="number"
                    placeholder="请输入计件标准"
                  ></el-input>
                  <!-- </el-form-item> -->
                </template>
              </el-table-column>
              <el-table-column
                label="计件金额"
                align="center"
                prop="amount"
              ></el-table-column>
              <el-table-column
                label="换版数量"
                min-width="120"
                align="center"
                prop="exchangeNum"
              >
                <template #default="scope">
                  <!-- <el-form-item :prop="'reportUserList.' + scope.$index + '.wagesPiece'"
                                            :rules="[{ required: true, message: '计件工资', trigger: 'blur' }]"> -->
                  <el-input
                    pattern="[0-9]*"
                    @blur="changeAmountH(scope.row, scope.$index)"
                    v-model="scope.row.exchangeNum"
                    type="number"
                    placeholder="请输入换版数量"
                  ></el-input>
                  <!-- </el-form-item> -->
                </template>
              </el-table-column>
              <el-table-column
                label="计件标准(换版)"
                min-width="120"
                align="center"
                prop="standardH"
              >
                <template #default="scope">
                  <!-- <el-form-item :prop="'reportUserList.' + scope.$index + '.wagesPiece'"
                                            :rules="[{ required: true, message: '计件工资', trigger: 'blur' }]"> -->
                  <el-input
                    pattern="[0-9]*"
                    @blur="changeAmountH(scope.row, scope.$index)"
                    v-model="scope.row.standardH"
                    type="number"
                    placeholder="请输入计件标准"
                  ></el-input>
                  <!-- </el-form-item> -->
                </template>
              </el-table-column>
              <el-table-column
                label="计件金额(换版)"
                align="center"
                prop="amountH"
              ></el-table-column>
              <el-table-column
                label="预计用纸令数"
                min-width="120"
                align="center"
                prop="expectLing"
              >
              </el-table-column>
              <el-table-column
                label="实际用纸令数"
                min-width="100"
                align="center"
                prop="realityLing"
              >
                <template #default="scope">
                  <el-input
                    :disabled="flag"
                    pattern="[0-9]*"
                    @blur="changeRealityLing(scope.row, scope.$index)"
                    v-model="scope.row.realityLing"
                    type="number"
                    placeholder="请输入实际用纸令数"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="盈亏令数"
                min-width="120"
                align="center"
                prop="ykLing"
              >
                <template #default="scope">
                  <el-input
                    :disabled="flag"
                    v-model="scope.row.ykLing"
                    type="number"
                    placeholder="请输入盈亏令数"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="累计已上报数量"
                align="center"
                prop="totalNum"
              ></el-table-column>
              <el-table-column
                label="最大允许上报数量"
                align="center"
                prop="maxNum"
              ></el-table-column>
              <el-table-column
                label="损耗比例"
                align="center"
                prop="lossCoefficient"
              ></el-table-column>
              <el-table-column
                label="备注"
                width="150"
                prop="remark"
                align="center"
              >
                <template #default="scope">
                  <el-input
                    v-model="scope.row.remark"
                    placeholder="请输入内容"
                  ></el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                v-if="!route.query.info"
                align="center"
                fixed="right"
                class-name="small-padding fixed-width"
              >
                <template #default="scope">
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleDeleteOrder(scope.row)"
                  ></el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </div>
      </el-collapse-item>
    </el-collapse>
    <userWorkListVue
      :visible="searchPeopleVisible"
      :userWorkList="userWorkList"
      @changeUpdate="changePeopleData"
      @cancel="
        () => {
          searchPeopleVisible = false;
        }
      "
    ></userWorkListVue>
    <pieceList
      :visible="pieceListOpen"
      @changeUpdate="changePieceListData"
      :orderSelectList="orderSelectList"
      :params="params"
      @cancel="
        () => {
          pieceListOpen = false;
        }
      "
    ></pieceList>
    <el-button class="footer" v-if="!flag" @click="submitForm">提交</el-button>
  </div>
</template>

<script setup>
import {
  addReportList,
  getReportById,
  listReportCare,
} from "@/api/production/printReport.js";
import userWorkListVue from "./userWorkList";
import useTagsViewStore from "@/store/modules/tagsView";
import Cookies from "js-cookie";
import useUserStore from "@/store/modules/user";
import pieceList from "./pieceList.vue";
import { encrypt } from "@/utils/jsencrypt";
import { toNumber } from "@/utils/ruoyi";
import { nextTick } from "vue";
import { ElMessage } from "element-plus";
import { getById } from "@/api/basicInfo/workbench";
const userStore = useUserStore();

const route = useRoute();
const router = useRouter();
const searchPeopleVisible = ref(false);
const pieceListOpen = ref(false);
const tagsViewStore = useTagsViewStore();
const { proxy } = getCurrentInstance();
const userInfo = useUserStore();
const peopleSelectList = ref([]);
const orderSelectList = ref([]);
const params = ref({});
const activeNames = ["1", "2", "3"];
const userRef = ref(null);
const reportUserListForm = ref(null);
const flag = ref(false);
const totalWagesSum = ref(0);
const totalAmount = ref(0);
const totalAmountH = ref(0);
const userWorkList = ref([]);
// const mes_paper_package = ref([])
// const ems_order_print_color = ref([])

const data = reactive({
  reportCareList: [], // 保养
  reportUserList: [], // 人员
  reportWorkList: [], // 完成
  form: {},
  rules: {
    reportDate: [
      { required: true, message: "报工日期不能为空", trigger: "blur" },
    ],
    createBy: [{ required: true, message: "上报人不能为空", trigger: "blur" }],
  },
});
const { form, rules, reportCareList, reportUserList, reportWorkList } =
  toRefs(data);
const { mes_paper_package, ems_order_print_color } = proxy.useDict(
  "mes_paper_package",
  "ems_order_print_color"
);

// 获取当前时间
const getCurrentDateTime = () => {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, "0");
  const day = String(now.getDate()).padStart(2, "0");
  form.value.dutyDate = `${year}-${month}-${day}`;
};
// 根据机台id 查询 机台
const getWorkBranch = () => {
  getById({ pid: route.query.id }).then((res) => {
    userWorkList.value = res.data.mesMachineUserList.map((item) => {
      return {
        ...item,
        name: item.mesUsers.name,
        code: item.mesUsers.code,
      };
    });
    form.value.machineName = res.data.machineName;
    form.value.machineId = res.data.pid;
    params.value = { machineId: res.data.pid };
    form.value.headName = res.data.headUserName;
    form.value.machineType = res.data.type;
    listReportCare({ status: 2, machineNo: res.data.machineNo }).then((res) => {
      reportCareList.value = res.data.map((item) => {
        return {
          code: item.code,
          timeLength: undefined,
          remark: undefined,
        };
      });
    });
  });
};

getCurrentDateTime();
nextTick(() => {
  form.value.createBy = userInfo.name;
});

if (route.query?.uid) {
  getReportById({ id: route.query.uid }).then((res) => {
    Object.assign(form.value, { ...res.data });
    reportCareList.value = res.data.reportCareList;
    reportUserList.value = res.data.reportUserList;
    reportWorkList.value = res.data.reportWorkList;
    if (route.query.info) {
      flag.value = true;
    }
  });
}

function limitInput(key, row) {
  row[key] =
    ("" + row[key]) // 第一步：转成字符串
      .replace(/[^\d^\.]+/g, "")
      .replace(/^0+(\d)/, "$1")
      .replace(/^\./, "0.")
      .match(/^\d*(\.?\d{0,1})/g)[0] || "";
  handleTotalCount();
}
const hanldeReportList = () => {
  router.push({
    path: "/reportList",
    query: {
      type: 1,
    },
  });
};
// 合计
const getSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    const values = data.map((item) => Number(item[column.property]));
    if (!values.every((value) => Number.isNaN(value))) {
      sums[index] = `${values.reduce((prev, curr) => {
        const value = Number(curr);
        if (!Number.isNaN(value)) {
          return toNumber(prev + curr, 2);
        } else {
          return toNumber(prev, 2);
        }
      }, 0)}`;
      if (column.property == "wagesPiece") {
        totalWagesSum.value = toNumber(Number(sums[index]), 2);
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};
// 合计
const getSummariesWorkList = (param) => {
  const { columns, data } = param;
  const sums = [];
  const fieldsToSum = ["amount", "amountH"];
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = "合计";
      return;
    }
    if (fieldsToSum.includes(column.property)) {
      const values = data.map((item) => Number(item[column.property]));
      if (!values.every((value) => Number.isNaN(value))) {
        sums[index] = ` ${values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!Number.isNaN(value)) {
            return toNumber(prev + curr, 2);
          } else {
            return toNumber(prev, 2);
          }
        }, 0)}`;
        if (column.property == "amount") {
          totalAmount.value = toNumber(sums[index], 2);
        }
        if (column.property == "amountH") {
          totalAmountH.value = toNumber(sums[index], 2);
        }
      } else {
        sums[index] = "";
      }
    } else {
      sums[index] = "";
    }
  });
  return sums;
};

const hanldeBack = () => {
  router.push("todo");
};
const mustPeople = (obj) => {
  let mustColumns = [3, 4];
  if (mustColumns.includes(obj.columnIndex)) {
    return "must";
  }
};

// 选择人员
const handleAddReportUserList = () => {
  peopleSelectList.value = reportUserList.value;
  searchPeopleVisible.value = true;
};
// 选中的人员
const changePeopleData = (row) => {
  const codeSet = new Set(reportUserList.value.map((data) => data.id));
  row.forEach((item) => {
    if (!codeSet.has(item.id)) {
      reportUserList.value.push({
        ...item,
        remark: null,
        no: item.code,
        wagesSubsidy: null,
        wagesPiece: null,
      });
      codeSet.add(item.id);
    }
  });
  reportUserList.value = reportUserList.value.filter((item) =>
    row.some((rowItem) => rowItem.id === item.id)
  );
  if (reportWorkList.value.length > 0) {
    handleTotalCount();
  }
  searchPeopleVisible.value = false;
};
// 合计工资
const changeWagesSum = (row, index) => {
  reportUserList.value[index].wagesSum =
    Number(row.wagesPiece) + Number(row.wagesSubsidy);
};
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    reportUserList.value = reportUserList.value.filter(
      (item) => item.id !== row.id
    );
    handleTotalCount();
    proxy.$modal.msgSuccess("删除成功");
  });
};
const handleDeleteOrder = (row) => {
  proxy.$modal.confirm("是否确认删除该数据？").then(function () {
    reportWorkList.value = reportWorkList.value.filter((item) =>
      item.id ? item.id !== row.id : item.pieceId != row.pieceId
    );
    handleTotalCount();
    proxy.$modal.msgSuccess("删除成功");
  });
};

// 选择生产单
const handleAddPieceList = () => {
  orderSelectList.value = reportWorkList.value;
  pieceListOpen.value = true;
};
// 选中的数据
const changePieceListData = (row) => {
  const codeSet = new Set(reportWorkList.value.map((data) => data.pieceId));
  row.forEach((item) => {
    if (!codeSet.has(item.pieceId)) {
      reportWorkList.value.push({
        ...item,
        fromType: "1", // 来源类型  1生产单， 2纸张
        bookCode: item.bookNo,
        orderName: item.bookName,
        labeling: item.pieceView,
      });
      codeSet.add(item.pieceId);
    }
  });
  reportWorkList.value.forEach((ele, index) => {
    changeAmount(ele, index);
    changeAmountH(ele, index);
  });
  pieceListOpen.value = false;
};

const handleTotalCount = () => {
  // 计算计件工资
  const totalLing = reportWorkList.value.reduce((prev, item) => {
    prev += Number(item.amount || 0) + Number(item.amountH || 0);
    return prev;
  }, 0);
  const totalProportion = reportUserList.value.reduce((prev, item) => {
    prev += Number(item.proportion || 0);
    return prev;
  }, 0);
  reportUserList.value.forEach((item) => {
    if (item.proportion) {
      item.wagesPiece = toNumber(
        (Number(item.proportion) / totalProportion) * totalLing,
        2
      );
      // item.wagesSum = toNumber(item.wagesPiece + Number(item.wagesSubsidy || 0), 2)
    }
  });
};
// 计算计件令数
const changePieceLing = (row, index) => {
  if (Number(row.finishNum) > Number(row.maxNum)) {
    row.finishNum = row.maxNum;
  }
  /** 实际用纸令数   realityLing
    平张：完成数量（计件令数）*印张/1000*（1+损耗系数）
    卷筒：完成数量（计件令数）*印张/1000*（1+损耗系数）/吨位系数
     */
  //   if (row.printType == 1) {
  //     // 平张
  //     row.realityLing = toNumber(
  //       ((Number(row.finishNum || 0) * Number(row.sheet || 0)) / 1000) *
  //         (1 + Number(row.lossCoefficient || 0)),
  //       4
  //     );
  //   } else {
  //     row.realityLing = toNumber(
  //       (((Number(row.finishNum || 0) * Number(row.sheet || 0)) / 1000) *
  //         (1 + Number(row.lossCoefficient || 0))) /
  //         Number(row.tonnageCoefficient || 1),
  //       4
  //     );
  //   }
  row.expectLing = toNumber(Number(row.finishNum || 0) / 1000, 4);
  row.realityLing = row.expectLing;
  row.ykLing = toNumber(row.expectLing - row.realityLing, 4);

  // if (
  //     Number(reportWorkList.value[index].finishNum) +
  //         Number(reportWorkList.value[index].totalNum) >
  //     Number(reportWorkList.value[index].maxNum)
  // ) {
  //     reportWorkList.value[index].finishNum = undefined
  //     return ElMessage({
  //         message: '完工数量+累计已上报数量不能大于最大允许上报数量',
  //         type: 'warning',
  //     })
  // }

  // 完工数量/1000 * 印张
  reportWorkList.value[index].pieceLing = toNumber(
    (Number(row.finishNum) || 0) / 1000,
    4
  );
  reportWorkList.value[index].amount = toNumber(
    (Number(reportWorkList.value[index].pieceLing) || 0) *
      (Number(row.standard) || 0),
    2
  );
  // changeAmount()
  handleTotalCount();
};
//  计算计件金额
const changeAmount = (row, index) => {
  // 计件令数*计件标准
  reportWorkList.value[index].amount = toNumber(
    Number(row.pieceLing || 0) * Number(row.standard || 0),
    2
  );
  handleTotalCount();
};
const changeRealityLing = (row, index) => {
  // 盈亏 预计-实际
  reportWorkList.value[index].ykLing = toNumber(
    Number(row.expectLing || 0) - Number(row.realityLing || 0),
    4
  );
};
//  计算计件金额（换版）
const changeAmountH = (row, index) => {
  // 换版数量*计件标准（换版）
  reportWorkList.value[index].amountH = toNumber(
    (Number(row.exchangeNum) || 0) * (Number(row.standardH) || 0),
    2
  );
  handleTotalCount();
};
//  返回
const goBack = () => {
  router.replace({ path: "/production/printReport" });
  setTimeout(() => {
    tagsViewStore.delView(route);
  }, 0);
};

// 清除主键
const clearId = (list, key) => {
  if (list.length > 0) {
    list.forEach((item) => {
      delete item[key];
    });
  }
};
// 保存
const submitForm = async () => {
  try {
    await userRef.value.validate();
    // await reportUserListForm.value.validate()
    // if (
    //     Number(totalWagesSum.value) !=
    //     Number(totalAmount.value) + Number(totalAmountH.value)
    // ) {
    //     return ElMessage({
    //         message: '合计工资与计件金额不符',
    //         type: 'warning',
    //     })
    // }
    form.value.type = 1; //印刷
    form.value.status = 1;
    await addReportList({
      ...form.value,
      reportCareList: reportCareList.value,
      reportUserList: reportUserList.value,
      reportWorkList: reportWorkList.value,
    });
    ElMessage({
      message: "提交成功",
      type: "success",
    });
    router.push("todo");
  } catch (error) {}
};
if (route.query.id) {
  getWorkBranch();
}
</script>

<style lang="scss" scoped>
.app {
  padding: 20px;
}

.footer {
  background-color: #eb722f;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 42px;
  line-height: 42px;
  z-index: 9999;
}

.title {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  line-height: 50px;
  box-sizing: border-box;
  font-weight: 700;
  font-size: 16px;
  .icon {
    width: 30px;
    height: 56px;
    border: 3px solid #eb722f;
    border-right: 0px;
    border-radius: 5px 0 0 5px;
    background-color: #fcf2e7;
    color: #eb722f;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .title-left {
    flex: 1;
    border: 3px solid #eb722f;
    // border-radius: 5px 0 0 5px;
    border-left: 0px;
    background-color: #fcf2e7;
    color: #eb722f;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .title-right {
    height: 56px;
    width: 100px;
    background-color: #eb722f;
    border-radius: 0 5px 5px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #fff;
  }
}
</style>
